from celery import Celery

from apps import app, db

celery_app = Celery('upload_tasks')

# 配置broker（这里用Redis）
celery_app.conf.update(
    broker_url='redis://localhost:6379/0',
    result_backend='redis://localhost:6379/0',
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    worker_prefetch_multiplier=1,
    celery_task_result_expires=60 * 60 * 24,  # 任务过期时间
    celery_timezone='Asia/Shanghai',  # 时区配置
    enable_utc=True,
    imports=['apps.tasks']
)

celery_app.config_from_object(app.config)


class SQLAlchemyTask(celery_app.Task):
    def __call__(self, *args, **kwargs):
        with app.app_context():
            return self.run(*args, **kwargs)

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        with app.app_context():
            # 任务完成后关闭数据库会话
            db.session.remove()


celery_app.Task = SQLAlchemyTask

# # # 自动发现任务
# celery_app.autodiscover_tasks(['common.oss_upload'])
#
# if __name__ == '__main__':
#     celery_app.start()
